<?php

namespace app;

use app\model\company\CompanyUser;
use app\model\table\log\OperateLog;
use app\model\tablenot\tool\Tool;
use think\App;
use function think\p;

/**
 * 带验证token基础类
 * Class VerifyController
 * @package app
 */
class  MyController
{
    /**
     * 应用实例
     */
    protected $app;
    protected $request;

    /**
     * 存放系统时间-很多地方使用，现在定义了后面直接用
     * @var false|string
     */
    public $time;

    /**
     * 用来临时存放返回数据里的data
     * @var
     */
    private $data = "";
    private $code = 200;
    private $message = "";

    // 保存所有用户登录信息
    public $user;
    public $token;

    public $post;
    public $get;

    private $stime;


    /**
     * @var array
     * 我来定义前置操作，所谓前置操作就是在我配置的操作执行之前执行我
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        $this->time = date("Y-m-d H:i:s", time());
        $this->stime = sprintf("%.5f", microtime(true)); // 记录请求开始时间
        $this->smemory = memory_get_usage(); // 记录请求开始内存
        $this->setGet();
        $this->setPost();
    }

    /**
     * 设置登录目标的用户信息
     * @param $userObj
     */
    public function setUser($userObj)
    {
        $this->user = $userObj;
    }

    // 防注入，get和post参数做处理
    public function setGet()
    {
        if ($this->app->request->isGet()) {
            $param1 = json_decode(file_get_contents('php://input'), true);
            $param1 = empty($param1) ? array() : $param1;
            $param2 = $this->request->get();
            foreach ($param1 as $key => $val) {
                $this->get[$key] = addslashes($val);
            }
            foreach ($param2 as $key => $val) {
                $this->get[$key] = addslashes($val);
            }
        }
        unset($this->post['token']);
    }

    // 防注入，get和post参数做处理
    public function setPost()
    {
        if ($this->app->request->isPost()) {
            $param1 = json_decode(file_get_contents('php://input'), true);
            $param1 = empty($param1) ? array() : $param1;
            $param2 = $this->request->post();
            foreach ($param1 as $key => $val) {
                if (!is_array($val)) {
                    $this->post[$key] = addslashes($val);
                } else {
                    $this->post[$key] = $val;
                }
            }
            foreach ($param2 as $key => $val) {
                if (!is_array($val)) {
                    $this->post[$key] = addslashes($val);
                } else {
                    $this->post[$key] = $val;
                }
            }
        }
        unset($this->post['token']);
    }

    public function setCode($code)
    {
        $this->code = $code;
    }

    public function getCode()
    {
        return $this->code;
    }

    public function setData($data)
    {
        $this->data = $data;
    }

    public function getData()
    {
        return $this->data;
    }

    public function setMessage($message)
    {
        $this->message = $message;
    }

    public function sendJson()
    {
        header('Content-type:application/json; charset=utf-8');
        $this->writeLog(json_encode($this->data, JSON_UNESCAPED_UNICODE));
        if (extension_loaded('zlib')) {
            ob_start('ob_gzhandler');
        }
        echo json_encode(
            array(
                'code' => $this->code,
                'message' => $this->message,
                'data' => $this->data,
            ), JSON_UNESCAPED_UNICODE
        );
        exit();
    }

    /**
     * 记录请求日志
     * 每次路由请求记录由这个方法写入
     * @param $content
     */
    public function writeLog($content)
    {
        // 如果内容长度大于1000字符就记录了，免得数据库过大
        $length = strlen($content);
        if ($length > 1000) {
            $content = "";
        }
        $HTTP_HOST = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : "";
        $REQUEST_URI = isset($_SERVER['REQUEST_URI']) ? explode("?", $_SERVER['REQUEST_URI'])[0] : "";
        $REQUEST_URI = str_replace('//', '/', $REQUEST_URI);
        $url = $HTTP_HOST . $REQUEST_URI . "?token=" . $this->token;

        if ($_SERVER['REQUEST_METHOD'] == "GET") {
            $params = json_encode($_GET, JSON_UNESCAPED_UNICODE);
        } else {
            if (empty($_POST)) {
                $params = file_get_contents('php://input');
            } else {
                $params = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            }
        }

        $postData = array(
            'name' => '接口请求',
            'url' => $url,
            'type' => $_SERVER['REQUEST_METHOD'],
            'params' => $params,
            'content' => $content,
            'use_time' => $this->stime ? sprintf("%.5f", microtime(true)) - $this->stime : "",
            'use_memory' => $length,
            'plat' => "",
            'operate_name' => $this->user['token'] ?? "",
            'created_at' => date("Y-m-d H:i:s", time()),
            'login_user_id' => $this->user['id'] ?? 0,
            'data_user_id' =>  $this->user['id'] ?? 0,
            'ip' => Tool::getRealIp(),
            'route' => request()->baseUrl()
        );
        OperateLog::instance()->add($postData);
    }

}